package westnovel

import (
	"github.com/PuerkitoBio/goquery"
	"net/http"
	"save-kindle/entity"
	"save-kindle/log"
	"save-kindle/source"
)

type WestNovel struct {
	source.BookInfo
	Catalog []entity.Article
}

func NewWestNovel(webSite string) *WestNovel {
	return &WestNovel{
		BookInfo: source.BookInfo{
			WebSite: webSite,
		},
	}
}

func (source *WestNovel) NewBook(bookId, bookName string) {
	source.BookName, source.BookId = bookName, bookId
	source.Catalog = make([]entity.Article, 0)
}

func (source *WestNovel) GetCatalog() ([]entity.Article, error) {
	req, err := http.NewRequest(http.MethodGet, source.WebSite+source.BookId, nil)
	if err != nil {
		log.PrintErr(err)
		return nil, err
	}

	client := http.Client{}
	do, err := client.Do(req)
	if err != nil {
		log.PrintErr(err)
		return nil, err
	}
	defer do.Body.Close()

	document, err := goquery.NewDocumentFromReader(do.Body)
	if err != nil {
		return nil, err
	}
	log.Println(document.Html())
	// 解析目录
	document.Find(".chapterlist").Each(func(i int, selection *goquery.Selection) {
		// <dd><a href=""></a></dd>
		selection.Find("dd").Each(func(ii int, ddTag *goquery.Selection) {
			attr, exists := ddTag.Find("a").Attr("href")
			if exists {
				article := entity.Article{
					ArticleUrl:  attr,
					ArticleName: ddTag.Text(),
				}
				source.Catalog = append(source.Catalog, article)
			}
		})
	})
	return source.Catalog, nil
}

// GetArticleContent 获取对应 articleIndex 文章内容
func (source *WestNovel) GetArticleContent(article entity.Article) (entity.Article, error) {
	log.Println(article)

	req, err := http.NewRequest(http.MethodGet, source.WebSite+article.ArticleUrl, nil)
	if err != nil {
		log.PrintErr(err)
		return article, err
	}

	client := &http.Client{}
	do, err := client.Do(req)
	if err != nil {
		log.PrintErr(err)
		return article, nil
	}
	defer do.Body.Close()

	document, err := goquery.NewDocumentFromReader(do.Body)
	if err != nil {
		log.PrintErr(err)
		return article, err
	}

	document.Find("#BookText").Each(func(i int, selection *goquery.Selection) {
		log.Println(selection.Html())
		log.Println(selection.Text())
		divTag := selection.Find("div")
		log.Println(divTag.Length())
		log.Println(divTag.Html())
		log.Println(divTag.Text())
		divTag.Each(func(i int, selection *goquery.Selection) {
			log.Println(selection.Html())
			log.Println(i, selection.Text())

		})
	})

	return article, nil
}
